package org.example.rental.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.rental.common.Result;
import org.example.rental.domain.Brand;
import org.example.rental.domain.Vehicle;
import org.example.rental.service.BrandService;
import org.example.rental.service.VehicleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/vehicle")
public class VehicleController extends BaseController{

    @Autowired
    VehicleService vehicleService;

    @Autowired
    BrandService brandService;

    @GetMapping("/info/{id}")
    public Result info(@PathVariable(name = "id") Long id){
        Vehicle vehicle = vehicleService.getById(id);

        return Result.succ(vehicle);
    }


    @GetMapping("/list")
    public Result list(String name,String vehNum){
        QueryWrapper<Vehicle> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(name),"name",name);
        queryWrapper.eq(StrUtil.isNotBlank(vehNum),"veh_num",vehNum);

        Page<Vehicle> page = vehicleService.page(getPage(),queryWrapper);

        return Result.succ(page);
    }




    @PostMapping("/save")
    public Result save(@Validated @RequestBody Vehicle vehicle){
        Brand brand = brandService.getById(vehicle.getBrandId());
        if (brand!=null){
            vehicle.setBName(brand.getName());
        }
        vehicle.setStatus(0);
        vehicleService.save(vehicle);
        return Result.succ(vehicle);
    }


    @PostMapping("/update")
    public Result update(@Validated @RequestBody Vehicle vehicle){
        System.out.println(vehicle.getBrandId());
        Brand brand = brandService.getById(vehicle.getBrandId());
        if (brand!=null){
            vehicle.setBName(brand.getName());
        }
        vehicleService.updateById(vehicle);
        return Result.succ(vehicle);
    }





    @PostMapping("/delete")
    @Transactional
    public Result delete(@RequestBody Long[] ids){
        //删除车辆
        vehicleService.removeByIds(Arrays.asList(ids));


        return Result.succ("车系删除成功");

    }


    @GetMapping("/selectVehicles")
    public Result selectVehicles(){
        List<Vehicle> list = vehicleService.list();
        return Result.succ(list);
    }



}
